#include "SpellManager.h"
#include "resourceManager.h"

void SpellManager::CastSpell(Entity & e, eSpell spell, vector3df & target)
{
	Spell * sp;
	bool free = false;
	int i = 0;
	while ((!free) && (i!=MAX_SPELLS))
	{
		sp = &Level::currentLevel->spells[i];
		if (!sp->isEnabled)
			free = true;
		else
			i++;
	}
	
	if ( free )
	{
		cout << "disparando spell" << endl;
		// play sound of flying ball
		ResourceManager::PlaySound(ResourceManager::SOUND::Impact,0.9f);
		ResourceManager::PlaySound(ResourceManager::SOUND::Ball);
		
		sp->position.set(e.position.X, e.position.Y, e.position.Z);
		sp->rotation.set(e.rotation.X, e.rotation.Y, 0);
		sp->speed.set(SPELL_SPEED,SPELL_SPEED,0);
		sp->sDamage=CPlayerGUI::m_nLevel * 2;
		sp->id=i;
		sp->type=eT_Spell;
		sp->sType=spell;
		sp->dam.isEnabled=false;
		sp->isEnabled=true;
		sp->isVisible=true;
		sp->isAlive=true;
		sp->radiusxz=3;
		sp->height=3;
		sp->id=e.id;
		sp->PartSyst = Level::smgr->addParticleSystemSceneNode(false);
		sp->PartSyst->setPosition(core::vector3df(0,0,0));
		sp->PartSyst->setScale(core::vector3df(0.01f,0.01f,0.01f));
		sp->PartSyst->setParticleSize(core::dimension2d<f32>(20.0f, 10.0f));
		
		scene::IParticleEmitter* em = sp->PartSyst->createPointEmitter(
			core::vector3df(
				3 * sin( target.Y * PI / 180.0f ) * cos( target.X * PI / 180.0f),
				3 * sin( target.X * PI / 180.0f),
				3 * cos( target.Y * PI / 180.0f ) * cos( target.X * PI / 180.0f)),
			//target - e.position,
			/*
				core::vector3df(
				3 * sin((sp->rotation.Y) * PI / 180.0f) * cos(sp->rotation.X*PI/180.0f),
				3 * sin(sp->rotation.X * PI / 180.0f),
				3 * cos((sp->rotation.Y) * PI / 180.0f) * cos(sp->rotation.X*PI/180.0f)),
			*/
			80, 100, 
			video::SColor(0,255,0,0), video::SColor(0,240,180,0),
			120, 280,
			45);

		sp->PartSyst->setEmitter(em);
		em->drop();

		scene::IParticleAffector* paf =  sp->PartSyst->createGravityAffector(vector3df(0,0,0));
		/*
								-3*sin((float)(sp->rotation.Y)*PI/180.0f)
										  *cos(sp->rotation.X*PI/180.0f),
								-3*sin(sp->rotation.X*PI/180.0f), 
								-3*cos((float)(sp->rotation.Y)*PI/180.0f)
										  *cos(sp->rotation.X*PI/180.0f);
		*/
		sp->PartSyst->addAffector(paf);
		paf->drop();
		sp->PartSyst->setPosition(sp->position);
		sp->PartSyst->setMaterialFlag(video::EMF_LIGHTING, false);
		sp->PartSyst->setMaterialTexture(0, Global::driver->getTexture("../media/roundPARTICLE.bmp"));
		sp->PartSyst->setMaterialType(video::EMT_TRANSPARENT_VERTEX_ALPHA);
		sp->lifeTime=800;
		sp->id = e.id;

		scene::ISceneNodeAnimator* anim =    Level::smgr->createCollisionResponseAnimator(
			Level::selector, sp->PartSyst, core::vector3df(2,2,2),
			core::vector3df(0,-3,0),
			core::vector3df(0,0,0));
		sp->PartSyst->addAnimator(anim);
		anim->drop();
	}
}
